<?php
	require 'connection.php';
	
	if(!isLogged())
	{
		header('location:login.php');
	}
	
	$id = $_GET['traktor_id'];
	$user = $_SESSION['username'];
	
	$tractorQuery = "SELECT `traktor_id`, `price`, `user_id` FROM `traktor` WHERE traktor_id = '$id'";
	$tractorRes = mysqli_query($db_connect, $tractorQuery) or die(mysqli_error($db_connect));
	
	$userQuery = "SELECT `user_id`, `username`, `money` FROM `user` 
					WHERE username= '$user'";
	$userRes = mysqli_query($db_connect, $userQuery) or die(mysqli_error($db_connect));
?>

<html>
<head>
	<title>Buy tractor</title>
	<link type="text/css" href="style/form_css.css" rel="stylesheet"/>
</head>
<body>
	<?php 
		$tractorRow = mysqli_fetch_assoc($tractorRes);
		$userRow = mysqli_fetch_assoc($userRes);
	
		echo "<div id='main'>";
		echo "<p>This item costs: " .$tractorRow['price']. "</p>";
		echo "<p>Your money: " . $userRow['money']. "</p>";
		
		
		$price = $tractorRow['price'];
		$money = $userRow['money'];
		
		
		if($price>$money)
		{
			echo "<h2>You can't afford this item!</h2>";
			echo "<a href=index.php><input type='button' value='Go Back'></a>";
			
		} else 
		{
			$finalSum = $money-$price;
			echo "<h2>You can buy this!</h2>";
			echo "<h4>Money left after buying: " . "$finalSum". "</h4>";
			echo "<form method='post'>";
			echo "<input name='submit' type='submit' value='Buy'>";
			echo "<a href=index.php><input type='button' value='Go Back'></a>";
			
		}
		
	echo "</div>";
	?>
</body>
</html>

<?php 
	if(isset($_POST['submit']))
	{
		$buyQuery = "UPDATE `traktor` SET `user_id`='$user' WHERE traktor_id='$id'";
		$buyRes = mysqli_query($db_connect, $buyQuery) or die(mysqli_error($db_connect));
		
	}
?>